<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Menu;

class MenuController extends Controller
{
    public function index(Request $request){
        $paginate = $request->has('paginate') ? $request->paginate : 15;
        $menu = Menu::paginate($paginate);
        return json_encode([
            'code' => '1',
            'data' => $menu
        ]);    
    }

    //获取一个
    public function get(Request $request){
        if(!$request->has('id')){
            return json_encode([
                'code' => '0',
                'data' => '请输入ID'
            ]);
        }
        $id = $request->id;
        $menu = Menu::find($id);
        return json_encode([
            'code' => '1',
            'data' => $menu
        ]);
    }

    //添加或者修改
    public function edit(Request $request){
        if(!$request->has('name') || !$request->has('url') || !$request->has('parent_id')){
            return json_encode([
                'code' => '0',
                'data' => '菜单名，url或者父级ID不能为空！'
            ]);
        }
        $sort_id = $request->has('sort_id') ? $request->sort_id : '0';
        if(!$request->has('id')){
            //add
            $menu = new Menu;
            $menu->name = $request->name;
            $menu->url = $request->url;
            $menu->parent_id = $request->parent_id;
            $menu->sort_id = $sort_id;
            $menu->save();
        }else{
            $menu = Menu::find($request->id);
            if(!$menu){
                return json_encode(['code'=>'0','data'=>'保存失败,ID不存在']);
            }
            $menu->name = $request->name;
            $menu->url = $request->url;
            $menu->parent_id = $request->parent_id;
            $menu->sort_id = $sort_id;
            $menu->save();
        }
        return json_encode([
            'code' => '1',
            'data' => '保存成功'
        ]);    
    }

    //删除
    public function del(Request $request){
        if(!$request->has('id')){
            return json_encode([
                'code' => '0',
                'data' => '请输入ID'
            ]);
        }
        $id = $request->id;
        Menu::destroy($id);
        return json_encode([
            'code' => '1',
            'data' => '删除成功'
        ]);
    }
}
